import React, { createContext, useContext, useState, useEffect } from 'react';
import { saveWebsites, loadWebsites } from '../utils/storage';

const WebsiteContext = createContext();

export const useWebsites = () => {
  const context = useContext(WebsiteContext);
  if (!context) {
    throw new Error('useWebsites must be used within a WebsiteProvider');
  }
  return context;
};

export const WebsiteProvider = ({ children }) => {
  const [websites, setWebsites] = useState(() => {
    console.log('=== WebsiteProvider 初始化 ===');
    const loadedWebsites = loadWebsites();
    console.log('WebsiteProvider初始化，加载的网站数据:', loadedWebsites);
    console.log('数据长度:', loadedWebsites?.length);
    return loadedWebsites;
  });
  const [currentWebsiteId, setCurrentWebsiteId] = useState(null);

  // 保存到localStorage并设置默认选中
  useEffect(() => {
    console.log('WebsiteContext - 保存数据到localStorage:', websites);
    saveWebsites(websites);
    
    // 如果没有默认网站，或者当前默认网站被禁用，选择第一个启用的网站
    const enabledWebsites = websites.filter(w => !w.disabled);
    const currentWebsite = websites.find(w => w.id === currentWebsiteId);
    
    if (!currentWebsiteId || !currentWebsite || currentWebsite.disabled) {
      if (enabledWebsites.length > 0) {
        setCurrentWebsiteId(enabledWebsites[0].id);
      } else {
        setCurrentWebsiteId(null);
      }
    }
  }, [websites, currentWebsiteId]);

  const addWebsite = (website) => {
    const newWebsite = {
      ...website,
      id: Date.now().toString(),
      disabled: false // 新添加的网站默认启用
    };
    setWebsites(prev => [...prev, newWebsite]);
  };

  const updateWebsite = (id, updatedWebsite) => {
    setWebsites(prev => 
      prev.map(website => 
        website.id === id ? { ...website, ...updatedWebsite } : website
      )
    );
  };

  const deleteWebsite = (id) => {
    setWebsites(prev => prev.filter(website => website.id !== id));
    if (currentWebsiteId === id) {
      const remaining = websites.filter(w => w.id !== id);
      setCurrentWebsiteId(remaining.length > 0 ? remaining[0].id : null);
    }
  };

  const setDefault = (id) => {
    const website = websites.find(w => w.id === id);
    if (website && !website.disabled) {
      setCurrentWebsiteId(id);
    }
  };

  const reorderWebsites = (newOrder) => {
    setWebsites(newOrder);
  };

  const toggleWebsiteStatus = (id) => {
    setWebsites(prev => 
      prev.map(website => 
        website.id === id ? { ...website, disabled: !website.disabled } : website
      )
    );
  };

  return (
    <WebsiteContext.Provider value={{
      websites,
      currentWebsiteId,
      addWebsite,
      updateWebsite,
      deleteWebsite,
      setDefault,
      reorderWebsites,
      toggleWebsiteStatus
    }}>
      {children}
    </WebsiteContext.Provider>
  );
};